package com.tarena.lbs.business.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.attach.api.AttachApi;
import com.tarena.lbs.attach.pojo.param.PicUpdateParam;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.business.constant.PictureTypes;
import com.tarena.lbs.business.dao.repository.BusinessRepository;
import com.tarena.lbs.business.dao.repository.StoreRepository;
import com.tarena.lbs.business.pojo.param.BusinessParam;

import com.tarena.lbs.business.pojo.po.BusinessPO;
import com.tarena.lbs.business.pojo.query.BusinessQuery;
import com.tarena.lbs.business.pojo.query.StoreQuery;
import com.tarena.lbs.business.pojo.vo.BusinessStoreVO;
import com.tarena.lbs.business.pojo.vo.BusinessVO;
import com.tarena.lbs.business.pojo.vo.StoreVO;
import com.tarena.lbs.business.service.BusinessService;
import com.tarena.lbs.common.enums.Roles;
import com.tarena.lbs.common.exception.ServiceException;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.response.StatusCode;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import io.jsonwebtoken.lang.Assert;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class BusinessServiceImpl implements BusinessService {
    @Autowired
    private BusinessRepository businessRepository;
    @Autowired
    private StoreRepository storeRepository;
    @DubboReference
    private AttachApi attachApi;

    @Override
    public PageResult<BusinessVO> selectList(BusinessQuery query) throws ServiceException {
        log.info("业务层查询商户列表:{}", query);
        //1.创建返回结果对象
        PageResult<BusinessVO> voPages= new PageResult<>();
        //2.调用仓储层 使用pageHelper查询 获取返回结果
        PageInfo<BusinessPO> pageInfo=businessRepository.getPages(query);
        //3.pageNum pageSize total可以直接封装
        voPages.setTotal(pageInfo.getTotal());
        voPages.setPageNo(pageInfo.getPageNum());
        voPages.setPageSize(pageInfo.getPageSize());
        //4.vos需要判断非空pos 转化
        List<BusinessVO> vos=null;
        if (CollectionUtils.isNotEmpty(pageInfo.getList())){
            vos=pageInfo.getList().stream().map(po->{
                BusinessVO vo=new BusinessVO();
                BeanUtils.copyProperties(po,vo);
                return vo;
            }).collect(Collectors.toList());
        }
        voPages.setObjects(vos);
        return voPages;
    }

    @Override
/*    public Integer save(BusinessParam param) throws ServiceException {
        //检查用户身份是否为管理员
        log.debug("检查用户身份是否为管理员");
        checkRole(Roles.ADMIN);
        Long count = businessRepository.selectByName(param.getBusinessName());
        if (count>0){
            throw new ServiceException(StatusCode.BUSINESSNAME_ALREADY_EXISTS);
        }
        BusinessPO bpo = new BusinessPO();
        BeanUtils.copyProperties(param, bpo);
        bpo.setEntryTime(new Date());
        log.info("业务层向持久层传输信息:{}", bpo);
        Integer id = businessRepository.save(bpo);
        bingPicture(id,param);
        return id;
    }*/
    public Integer save(BusinessParam param) throws ServiceException {
        // 检查用户身份是否为管理员
        log.debug("检查用户身份是否为管理员");

        try {
            UserPrinciple userPrinciple = AuthenticationContextUtils.get();
            log.info("当前用户信息: {}", userPrinciple);

            if (userPrinciple == null || userPrinciple.getRole() == null) {
                throw new ServiceException(StatusCode.USER_NOT_LOGIN.getCode(),
                        "用户未登录，请先登录");
            }

            if (userPrinciple.getRole() != Roles.ADMIN) {
                throw new ServiceException(StatusCode.USER_PERMISSION_DENIED.getCode(),
                        String.format("用户权限不足，需要管理员权限，当前角色: %s", userPrinciple.getRole()));
            }

        } catch (ServiceException e) {
            // 直接重新抛出业务异常
            throw e;
        } catch (Exception e) {
            // 其他异常转换为业务异常
            log.error("检查用户权限时发生异常: ", e);
            throw new ServiceException(StatusCode.SYSTEM_ERROR.getCode(),
                    "系统异常，无法验证用户权限");
        }

        // 检查商家名称是否已存在
        Long count = businessRepository.selectByName(param.getBusinessName());
        if (count > 0) {
            throw new ServiceException(StatusCode.BUSINESSNAME_ALREADY_EXISTS.getCode(),
                    String.format("商家名称 '%s' 已存在", param.getBusinessName()));
        }

        try {
            // 保存商家信息
            BusinessPO bpo = new BusinessPO();
            BeanUtils.copyProperties(param, bpo);
            bpo.setEntryTime(new Date());
            log.info("业务层向持久层传输信息:{}", bpo);

            Integer id = businessRepository.save(bpo);
            bingPicture(id, param);

            return id;

        } catch (Exception e) {
            log.error("保存商家信息失败: ", e);
            throw new ServiceException(StatusCode.SYSTEM_ERROR.getCode(),
                    "保存商家信息失败，请稍后重试");
        }
    }

    private void bingPicture(Integer id, BusinessParam param) throws ServiceException {
        log.debug("绑定图片");
        List<PicUpdateParam> picParam =new ArrayList<>();
        //绑定执照
        PicUpdateParam licenseParam = new PicUpdateParam();
        licenseParam.setBusinessId( id);
        licenseParam.setBusinessType(PictureTypes.BIZ_LICENSE);
        String licenseUrl=param.getBusinessLicense();
//        licenseParam.setFileUuid(getFileUuidFromUrl(licenseUrl));
        licenseParam.setFileUuid(licenseUrl);
        picParam.add(licenseParam);
        //绑定logo
        PicUpdateParam logoParam = new PicUpdateParam();
        logoParam.setBusinessId(id);
        logoParam.setBusinessType(PictureTypes.BIZ_LOGO);
        String logoUrl=param.getBusinessLogo();
//        logoParam.setFileUuid(getFileUuidFromUrl(logoUrl));
        logoParam.setFileUuid(logoUrl);
        picParam.add(logoParam);
        Boolean result=attachApi.batchUpdateBusiness(picParam);
        if (!result){
            throw new ServiceException(StatusCode.PICTURE_BIND_ERROR);
        }
    }
/*
    private String getFileUuidFromUrl(String url) throws BusinessException {
        try {
            if (url == null || url.trim().isEmpty()) {
                throw new BusinessException("-1", "图片URL不能为空");
            }

            String[] parts = url.split("/");
            if (parts.length < 5) {
                throw new BusinessException("-1", "图片URL格式不正确: " + url);
            }

            String fileUuid = parts[4];
            log.info("获取当前url:{};的fileUuid:{}", url, fileUuid);
            return fileUuid;

        } catch (BusinessException e) {
            throw e; // 重新抛出业务异常
        } catch (Exception e) {
            throw new BusinessException("-1", "解析图片URL失败: " + e.getMessage());
        }
    }

 */
    private void checkRole(Roles roles) throws ServiceException {
        log.debug("检查用户身份是否为管理员");
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        log.info("当前用户信息: {}", userPrinciple);
        if (userPrinciple.getRole() == null  ){
            throw new ServiceException(StatusCode.USER_NOT_LOGIN);
        }else if (userPrinciple.getRole() != roles){
            throw new ServiceException(StatusCode.USER_PERMISSION_DENIED);
        }
    }

    @Override
    public BusinessStoreVO getBusinessById(Integer businessId) throws ServiceException {
        checkRole(Roles.SHOP);
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        log.info("业务层查询商户信息:{}", businessId);
        if (userPrinciple.getId() != businessId || userPrinciple.getRole() != Roles.ADMIN){
            throw new ServiceException(StatusCode.USER_PERMISSION_DENIED);
        }
        BusinessStoreVO bvo = businessRepository.selectByBusinessId(businessId);
        StoreQuery storeQuery = new StoreQuery();
        storeQuery.setBusinessId(businessId);
        List<StoreVO> storeVOS = storeRepository.select(storeQuery);
        bvo.setStoreVOList(storeVOS);
        return bvo;
    }
}